<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport"
    content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
  <meta name="description" content="Create 3D models using glTF." />
  <meta name="cesium-sandcastle-labels" content="Tutorials,Showcases" />
  <title>Cesium Demo</title>
  <script type="text/javascript" src="../Sandcastle-header.js"></script>
  <script type="text/javascript" src="../../../Build/CesiumUnminified/Cesium.js" nomodule></script>
  <script type="module" src="../load-cesium-es6.js"></script>
</head>

<body class="sandcastle-loading" data-sandcastle-bucket="bucket-requirejs.html">
  <style>
    @import url(../templates/bucket.css);

    .kMpoIL {
      display: flex;
      gap: 8px;
      position: relative;
      left: -200px;
    }

    .cesium-viewer-toolbar {
      display: block;
      position: absolute;
      top: 5px;
      right: 423px;
    }
  </style>
  <div id="cesiumContainer" class="fullSize"></div>
  <div id="loadingOverlay">
    <h1>Loading...</h1>
  </div>
  <div id="toolbar"></div>
  <div style="position: fixed; top:10px; right: 50%;">
    <button onclick="setPosition();">设置位置</button>
    <button onclick="focusFly();">跟踪飞机</button>
    <button onclick="playProject();">播放</button>
    <br>
    <input id="newPosLat" />
    <br>
    <input id="newPoslon" />
  </div>
  <script id="cesium_sandcastle_script" type="module">
    // only import core
    import 'https://cdn.jsdelivr.net/npm/@theatre/browser-bundles@0.5.0-insiders.88df1ef/dist/core-and-studio.js'
    // We can now access Theatre.core and Theatre.studio from here
    const { core, studio } = Theatre

    window.startup = function (Cesium) {
      "use strict";
      Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlMmQ5OWE1ZS04ODMwLTQ5NmUtODk1Zi05OWVlOWM2NGQ2ZDYiLCJpZCI6MTY0NTgsInNjb3BlcyI6WyJhc3IiLCJnYyJdLCJpYXQiOjE1NzA1ODUxNTJ9.FUzgQG6PqlpXsLAu2-zlAxK8Z3g1aZTC8Hwr7i9cBFc";
      //Sandcastle_Begin
      const viewer = new Cesium.Viewer("cesiumContainer", {
        infoBox: false,
        selectionIndicator: false,
        shadows: true,
        shouldAnimate: true,
      });

      viewer.scene.globe.maximumScreenSpaceError = 2; // Set maximum screen space error for terrain rendering
      viewer.scene.globe.maximumMemoryCapacity = 512; // Set maximum memory capacity for terrain imagery (in MB)

      function createModel(url, height) {
        viewer.entities.removeAll();

        const position = Cesium.Cartesian3.fromDegrees(
          113.2979581,
          23.39251352,
          height
        );
        const heading = Cesium.Math.toRadians(-105);
        const pitch = 0;
        const roll = 0;
        const hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
        const orientation = Cesium.Transforms.headingPitchRollQuaternion(
          position,
          hpr
        );

        const entity = viewer.entities.add({
          name: url,
          position: position,
          orientation: orientation,
          model: {
            uri: url,
            minimumPixelSize: 128,
            maximumScale: 20000,
          },
        });


        viewer.camera.setView({
          destination: position,
        });

        window.entity = entity;
      }

      function setPosition() {
        let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        viewer.scene.globe.depthTestAgainstTerrain = true;
        handler.setInputAction((movement) => {
          const pickedPosition = viewer.scene.pickPosition(movement.position);
          if (Cesium.defined(pickedPosition)) {
            const cartographic = Cesium.Cartographic.fromCartesian(pickedPosition);
            const longitude = Cesium.Math.toDegrees(cartographic.longitude);
            const latitude = Cesium.Math.toDegrees(cartographic.latitude);
            const height = cartographic.height;

            // Update the model's position based on the clicked location
            if (window.entity) {
              window.entity.position = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);

              document.getElementById('newPosLat').value = latitude
              document.getElementById('newPoslon').value = longitude
            }
          }
          viewer.scene.globe.depthTestAgainstTerrain = false;
          // Remove the event after the first click
          handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      }
      window.setPosition = setPosition;

      window.isFocusFly = false;
      function focusFly() {
        window.isFocusFly = !window.isFocusFly;
        if (window.isFocusFly)
          viewer.trackedEntity = window.entity;
        else {
          viewer.trackedEntity = undefined;
        }
      }
      window.focusFly = focusFly;
      window.isplaying=false;
      function playProject() {
        if(!window.isplaying)
          window.sheet.sequence.play({ iterationCount: Infinity, range: [0, 145] })
        else
          window.sheet.sequence.pause();
        window.isplaying=!window.isplaying;
        return;
        fetch('state.json')
          .then(response => {
            if (!response.ok) {
              throw new Error('Network response was not ok');
            }
            window.project.state= response.json();
            // wait for project to be ready
            window.project.ready.then(() => {
              
            });
          })
          .then(data => {
            console.log('State data:', data);
            // You can add additional logic here to handle the downloaded data
          })
          .catch(error => {
            console.error('There was a problem with the fetch operation:', error);
          });
      }
      window.playProject = playProject;

      studio.initialize() // Start the Theatre.js UI
      // We can now access just Theatre.core from here

      const project = core.getProject('HTML Animation Tutorial')
      window.project=project;
      const sheet = project.sheet('Sheet 1');
      window.sheet= sheet;
      sheet.sequence.playbackRange = [0, 60]; // 设置时间轴范围为 0~60 秒
      const obj = sheet.object('Heading 1', {
        y: core.types.number(1, { range: [0, 1000000] }), // you can use just a simple default value
        lat: core.types.number(23.39251352, { range: [20, 50] }), // you can use just a simple default value,
        lon: core.types.number(113.2979581, { range: [112, 144] }), // you can use just a simple default value
        heading: core.types.number(-105, { range: [-180, 180] }), // you can use just a simple default value
      });

      obj.onValuesChange((obj) => {
        const position = Cesium.Cartesian3.fromDegrees(
          obj.lon,
          obj.lat,
          obj.y
        );
        const heading = Cesium.Math.toRadians(obj.heading);
        const pitch = 0;
        const roll = 0;
        const hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
        const orientation = Cesium.Transforms.headingPitchRollQuaternion(
          position,
          hpr
        );
        if (window.entity) {
          window.entity.position = position; // Adjusting the entity's position directly
          window.entity.orientation = orientation;
        }

      })

      

      const options = [
        {
          text: "Aircraft",
          onselect: function () {
            createModel(
              "../../SampleData/models/CesiumAir/Cesium_Air.glb",
              5000.0
            );
          },
        },
        {
          text: "Drone",
          onselect: function () {
            createModel(
              "../../SampleData/models/CesiumDrone/CesiumDrone.glb",
              150.0
            );
          },
        },
        {
          text: "Ground Vehicle",
          onselect: function () {
            createModel(
              "../../SampleData/models/GroundVehicle/GroundVehicle.glb",
              0
            );
          },
        },
        {
          text: "Hot Air Balloon",
          onselect: function () {
            createModel(
              "../../SampleData/models/CesiumBalloon/CesiumBalloon.glb",
              1000.0
            );
          },
        },
        {
          text: "Milk Truck",
          onselect: function () {
            createModel(
              "../../SampleData/models/CesiumMilkTruck/CesiumMilkTruck.glb",
              0
            );
          },
        },
        {
          text: "Skinned Character",
          onselect: function () {
            createModel(
              "../../SampleData/models/CesiumMan/Cesium_Man.glb",
              0
            );
          },
        },
        {
          text: "Draco Compressed Model",
          onselect: function () {
            createModel(
              "../../SampleData/models/DracoCompressed/CesiumMilkTruck.gltf",
              0
            );
          },
        },
        {
          text: "KTX2 Compressed Balloon",
          onselect: function () {
            if (!Cesium.FeatureDetection.supportsBasis(viewer.scene)) {
              window.alert(
                "This browser does not support Basis Universal compressed textures"
              );
            }
            createModel(
              "../../SampleData/models/CesiumBalloonKTX2/CesiumBalloonKTX2.glb",
              1000.0
            );
          },
        },
      ];

      Sandcastle.addToolbarMenu(options);
      //Sandcastle_End
      Sandcastle.finishedLoading();
    };
    if (typeof Cesium !== "undefined") {
      window.startupCalled = true;
      window.startup(Cesium);
    }


  </script>

</body>
<style>
  .kMpoIL {
    display: flex;
    gap: 8px;
    position: relative;
    left: -200px;
  }

  .cesium-viewer-toolbar {
    display: block;
    position: absolute;
    top: 5px;
    right: 423px;
  }
</style>

</html>